package com.smap.core;

import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import com.smap.common.Utils;

/**
 * an object on map
 * 
 * @author Shen
 */
public class Marker extends Composite {
	public XY location;
	protected HTML html;
	protected Map map;
	protected AbsolutePanel root;
	protected AbsolutePanel rootFront;

	public Marker() {
		html = new HTML();
		this.initWidget(html);
	}

	public Marker(double x, double y, String innerHtml) {
		this();
		set(new XY(x, y), innerHtml);
	}

	public Marker set(XY location, String innerHtml) {
		this.location = location; 
		html.setHTML(innerHtml);
		return this;
	}

	public void install(Map map) {
		this.map = map;
	}

	public void init() {
		root = this.map.getRoot();
		rootFront = this.map.getRootFront();
		rootFront.add(this);
	}

	protected void addToBack(Widget widget) {
		Utils.setZIndex(widget, 100);
		root.add(widget);
	}

	public void remove() {
		rootFront.remove(this);
		root.remove(this);
	}

	public void draw() {
		if (root == null) {
			init();
		}
		XY mapLocation = this.map.mapToPixel(this.location);
		setPosition(mapLocation);
	}

	public Marker project(Projection proj) {
		proj.project(location);
		return this;
	}

	Integer offsetX;
	Integer offsetY;

	public void setCenter(int x, int y) {
		offsetX = -x;
		offsetY = -y;
	}

	public XY setPosition(XY xy) {
		// offset
		int x1 = 0;
		int y1 = 0;
		if (offsetX != null) {
			x1 = offsetX;
			y1 = offsetY;
		} else {
			x1 = -this.getOffsetWidth() / 2;
			y1 = -this.getOffsetHeight() / 2;
		}
		XY pos = new XY(xy.x + x1, xy.y + y1);
		Utils.setPosition(this, (int) pos.x, (int) pos.y);
		return pos;
	}

}
